<?php

namespace Common\Mqtt\Utility;

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;

class MqttUtility
{
    /**
     * 获取全局配置
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getGlobalConfig(): array
    {
        /**
         * @var ConfigInterface $config
         */
        $config = ApplicationContext::getContainer()->get(ConfigInterface::class);
        return $config->get('mqtt');
    }


    public function getMQTT5ConnectConfig(): ClientConfig
    {
        $mqttConfig = $this->getGlobalConfig();
        $config = new ClientConfig();
        return $config->setUserName($mqttConfig['UserName'])
            ->setPassword($mqttConfig['Password'])
            ->setClientId(Client::genClientID())
            ->setKeepAlive($mqttConfig['KeepAlive'])
            ->setDelay($mqttConfig['Delay']) // 3s
            ->setMaxAttempts($mqttConfig['MaxAttempts'])
            ->setProperties($mqttConfig['Properties'])
            ->setProtocolLevel(5)
            ->setSwooleConfig($mqttConfig['SwooleConfig']);
    }

    /**
     * 获取客户端
     * @param array $will 遗嘱消息
     * @throws \Exception
     */
    public function getClient(array $will = []): Client
    {
        try {
            $mqttConfig = $this->getGlobalConfig();
            $Client = new Client($mqttConfig['ip'], $mqttConfig['port'], $this->getMQTT5ConnectConfig());
            $Client->connect(true, $will);
            return $Client;
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
            throw new \Exception('获取mqtt配置失败'.$e->getMessage());
        }
    }

    function isWebSocketConnection($server,$fd)
    {
        return $server->isEstablished($fd);
    }
}